package com.xsm.activitygroup;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import cn.bidaround.youtui_template.YouTuiViewType;
import cn.bidaround.youtui_template.YtTemplate;
import cn.bidaround.ytcore.data.ShareData;

import com.Zxing.Demo.CaptureActivity;
import com.umeng.analytics.MobclickAgent;
import com.xsm.DataBase.ReadMessage;
import com.xsm.DataBase.SaveMessage;
import com.xsm.internet.PostMessage;
import com.xsm.object.CTextObject;
import com.xsm.takephoto.TakePhotoDialog;
import com.xsm.view.ClearEditText;
import com.xsm.view.LoadDialog;
import com.xsm.view.Mydialog;
public class activity3 extends Activity{
	private Spinner spi2,spi3;
	private Button bt1;
	private AutoCompleteTextView day;
	private LinearLayout typelayout;
	private Activity context;
	private String place="全部",selltype="出售";
	private RelativeLayout errorlayout,loadlayout;
	private LinearLayout issuesuccess;
	private LinearLayout issueLayout;
	private ClearEditText  contentEditText,bookname,bookprice,Author,pressEditText;
	private Button issuebutton,clearbutton;
	private  String textbookcid="-1";
	private  String press;
	private  String typeString;
	private  LinearLayout checkLogin;
     private long exitTime = 0;
     private  String userid;
     private  String paths;
     private  LinearLayout photos;
     private  int num=0;
     private  LoadDialog prodialog;
     private  String result="";
     private  Myhandler handler;
     private  String authorString="";
     private String booknameString="";
     private int authorsearch=0;//0在运行1结束2正在运行
     private int booknamesearch=0;//0在运行1结束2正在运行
     private  MyAdapter<String> pressAdapter;
     private MyAdapter<String> authorAdapter;
     private  MyAdapter<String> booknameAdapter;
     private  ArrayList<String> pressList;
     private  ArrayList<String> authorList;
     private ArrayList<String> booknameList;
     private SharedPreferences sharedPreferences;
     private Button zxing;
     private String ISBN;
	protected void onCreate(Bundle savedInstanceState) {
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity3);
	context=this;
	photos=(LinearLayout)findViewById(R.id.photos);
	handler=new Myhandler();
	 YtTemplate.init(this);/*初始化友推*/

	zxing =(Button)findViewById(R.id.zxing);
	zxing.getBackground().setAlpha(180);
	loadlayout=(RelativeLayout)findViewById(R.id.loadlayout);
	errorlayout=(RelativeLayout)findViewById(R.id.errorlayout);
	issueLayout=(LinearLayout)findViewById(R.id.issueLayout);
	issuesuccess=(LinearLayout)findViewById(R.id.issuesuccess);
	checkLogin=(LinearLayout)findViewById(R.id.checkLogin);
	
	issuebutton=(Button)findViewById(R.id.issuebutton);
	clearbutton=(Button)findViewById(R.id.clear);
	issuebutton.getBackground().setAlpha(180);
	clearbutton.getBackground().setAlpha(180);
	
	sharedPreferences=context.getSharedPreferences("XSM", 0);
	 press=sharedPreferences.getString("Press", "");
	 typeString=sharedPreferences.getString("Type","");
	 String user=sharedPreferences.getString("User","");
     userid=sharedPreferences.getString("User", "");
	 
	 if(user.equals("")){
		issueLayout.setVisibility(View.GONE);
		issuebutton.setVisibility(View.GONE);
		clearbutton.setVisibility(View.GONE);
		checkLogin.setVisibility(View.VISIBLE);
	 }else {
			if(press.equals("")||typeString.equals("")){
				loadlayout.setVisibility(View.VISIBLE);
				issueLayout.setVisibility(View.GONE);
				issuebutton.setVisibility(View.GONE);
				clearbutton.setVisibility(View.GONE);
				new init().execute();
			}else {
			    authorString=sharedPreferences.getString("author", "");
			    booknameString=sharedPreferences.getString("bookname", "");
				initView();	
				new initEdit().execute();			
				new Thread(new getAuthor()).start();	 		
			    new Thread(new getBookname()).start();	 
			}
			}	 
}

	
	public void ZXING(View view){
		startActivityForResult(new Intent(context,CaptureActivity.class), 2);
	}
	
	


	private void UploadMessage(){
		prodialog=new LoadDialog(context, "正在发布...");
		prodialog.showDialog();
		String price="";
		String name=bookname.getText().toString().trim();
	     price=bookprice.getText().toString().trim();	
	 String press=pressEditText.getText().toString().trim();
	 String bookmessage=contentEditText.getText().toString().trim();
	 String author=Author.getText().toString().trim();
	 
	 if(price.equals("")|price.equals("")|press.equals("")|author.equals("")){
		 Toast.makeText(context, "请输入完整的信息", Toast.LENGTH_LONG).show();
			issuebutton.setEnabled(true);
			prodialog.dissmissDialog();
		 return;
	 }else {
		if(selltype.equals("出租"))
		if(day.getText().toString().trim().equals(""))
		{
			 Toast.makeText(context, "请输入完整的信息", Toast.LENGTH_LONG).show();
				issuebutton.setEnabled(true);
				prodialog.dissmissDialog();
			 return;
		}
	  	
		if(textbookcid.equals("-1")){
			 Toast.makeText(context, "请选择书籍类型", Toast.LENGTH_LONG).show();
				issuebutton.setEnabled(true);
				prodialog.dissmissDialog();
			 return;
		}
	}
	new Issucetask(userid, name, price, selltype,textbookcid, bookmessage,press,place,author) .execute();
	}
	
	public void Login(View view){
		startActivity(new Intent(context,Login.class));
		finish();
	}
	
	public void Clear(View view){
		 contentEditText.setText("");
		 bookname.setText("");
		 Author.setText("");
		 pressEditText.setText("");
		 bookprice.setText("");
		  textbookcid="-1";
		 bt1.setText("书籍类型");
	}
private void initView(){
    pressList=new ArrayList<String>();
    authorList=new ArrayList<String>();
    booknameList=new ArrayList<String>();
	final String s2[]=new String[]{"广州中医药大学","广东药学院","华南理工大学","广东工业大学","广州大学","广州美术学院","华南师范大学","星海音乐学院","中山大学","广东外语外贸大学"};
	final String s3[]=new String[]{"出售"};
	String dvalue[]=new String[]{"1","10","30"};
	pressEditText=(com.xsm.view.ClearEditText )findViewById(R.id.press);
	contentEditText=(com.xsm.view.ClearEditText )findViewById(R.id.bookmessage);
	bookname=(com.xsm.view.ClearEditText )findViewById(R.id.bname);
	bookprice=(com.xsm.view.ClearEditText )findViewById(R.id.bookprice);
	Author=(com.xsm.view.ClearEditText )findViewById(R.id.author);
	
    String s[]=authorString.split(",");	
    for(int i=0;i<s.length;i++){
    	authorList.add(s[i]);
    }
    authorAdapter=new MyAdapter<String>(context, android.R.layout.simple_dropdown_item_1line,authorList);
    Author.setAdapter(authorAdapter);
	
	day=(AutoCompleteTextView)findViewById(R.id.day);	
	ArrayAdapter<String> dayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,dvalue);   
     day.setAdapter(dayAdapter);
     
     pressAdapter=new MyAdapter<String>(context, android.R.layout.simple_dropdown_item_1line,pressList);
    pressEditText.setAdapter(pressAdapter);

    
    String bb[]=booknameString.split(",");	
    for(int i=0;i<bb.length;i++){
    	booknameList.add(bb[i]);
    }
    booknameAdapter=new MyAdapter<String>(context, android.R.layout.simple_dropdown_item_1line,booknameList);
   bookname.setAdapter(booknameAdapter);
    
	spi2=(Spinner)findViewById(R.id.spi2);
	spi3=(Spinner)findViewById(R.id.spi3);
	 ArrayAdapter<String> adapter2=new ArrayAdapter<String>(this, R.layout.myspinner,s2);
	 ArrayAdapter<String> adapter3=new ArrayAdapter<String>(this, R.layout.myspinner,s3);
	 spi2.setAdapter(adapter2);
	 spi3.setAdapter(adapter3);
	 
	 typelayout=(LinearLayout)findViewById(R.id.typelayout);
	 spi2.setOnItemSelectedListener(new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			place=s2[arg2];
		}
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	 });
	 
	spi3.setOnItemSelectedListener(new OnItemSelectedListener() {
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			selltype=s3[arg2];
			if(arg2==1){
				typelayout.setVisibility(View.VISIBLE);
			}else {
				typelayout.setVisibility(View.GONE);	
			}
		}
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	
	});
	 
	bt1=(Button)findViewById(R.id.typebt);
	bt1.setText("书籍类型");
	bt1.setOnClickListener(new OnClickListener() {
		public void onClick(View arg0) {
			bt1.setEnabled(false);		
			new Thread(new TurnThread()).start();
		}
	});
	
}


public void Guanli(View view){
	startActivity(new Intent(context,Trade.class));
}

public void issuetrice(View view){
	issueLayout.setVisibility(View.VISIBLE);
	issuesuccess.setVisibility(View.GONE);
	issuebutton.setVisibility(View.VISIBLE);
	clearbutton.setVisibility(View.VISIBLE);
}




public void Share(View view){
	  YtTemplate blackTemp = new YtTemplate(context, YouTuiViewType.WHITE_GRID,false);  //白色网格样式不需要积分活动
	ShareData shareData = new ShareData();
	shareData.isAppShare = false;//设置为true则分享的信息从友推后台填写的应用信息中读取，可动态更新，后面的值不用设置。
	shareData.setDescription("书集二手书籍交易平台");
	shareData.setTitle("Hi,我刚在书集上发布了一本书<<"+bookname.getText().toString().trim()+">>,快来看看吧");
	shareData.setText("Hi,我刚在书集上发布了一本书<<"+bookname.getText().toString().trim()+">>,快来看看吧");
	shareData.setTarget_url("http://zhushou.360.cn/detail/index/soft_id/1757867");
	shareData.setImageUrl("http://shuji520.duapp.com/ShujiService/Apk/shujilogo.png");
	blackTemp.setShareData(shareData);//设置默认的分享数据;shareData 设置参看4.6
	blackTemp.show();
	
}





class  Holder{
	int num;
	String path;
}

	
	
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//书籍类型
	if(requestCode==1){
		if(resultCode==RESULT_OK){
		String textid=data.getExtras().getString("textid");
		String textString=data.getExtras().getString("textString");
		bt1.setText(textString);
		textbookcid=textid;	}
	}
    //二维码扫描
	else if(requestCode==2){
		if(resultCode==RESULT_OK){
			
			String describe=data.getExtras().getString("describe");
			String name=data.getExtras().getString("bookname");
			String press=data.getExtras().getString("press");
			String author=data.getExtras().getString("author");
			ISBN=data.getExtras().getString("ISBN");
			textbookcid=data.getExtras().getString("textcid");
			bt1.setText(data.getExtras().getString("textString"));
			contentEditText.setText(describe);
			bookname.setText(name);
			pressEditText.setText(press);
			Author.setText(author);
		}
	}
}

public void Issue(View view){	
	issuebutton.setEnabled(false);	
     UploadMessage();

}


public void Update(View view){
	errorlayout.setVisibility(View.GONE);
	loadlayout.setVisibility(View.VISIBLE);
	issueLayout.setVisibility(View.GONE);
	new init().execute();
}

public class init extends AsyncTask<Void, Void, String>{
	protected String doInBackground(Void... params) {
		 String reString="";
		 if(press.equals(""))
		 new SaveMessage(context).initPress();	
		 if(typeString.equals(""))
		 new SaveMessage(context).initType();	
		 
		 SharedPreferences sharedPreferences=context.getSharedPreferences("XSM", 0);
			String press1=sharedPreferences.getString("Press", "");
			String typeString1=sharedPreferences.getString("Type", "");
			
			if(typeString1.equals("")||press1.equals(""))
				reString="no";
			else {
				reString="yes";
			}
		return reString;
	}
	protected void onPostExecute(String result) {
		if(result.equals("yes")){
			loadlayout.setVisibility(View.GONE);
			issueLayout.setVisibility(View.VISIBLE);
			errorlayout.setVisibility(View.GONE);
			issuebutton.setVisibility(View.VISIBLE);
			clearbutton.setVisibility(View.VISIBLE);
			initView();
		}else {
		 	loadlayout.setVisibility(View.GONE);
        	errorlayout.setVisibility(View.VISIBLE);
		}
	}
	}

public void BookMessage(View view){
	contentEditText.requestFocus();
	InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
	imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}


public class Issucetask extends AsyncTask<Void, Void, String>{
	String userid="";
	String name="";
	String price="";
	String selltype="";
	String booktype="";
	String bookmessage="";
	String press="";
	String author;
String school="";
	public Issucetask(String userid,String name,String price,String selltype,String booktype,String bookmessage,String press,String school,String author){
		this.userid=userid;
		this.name=name;
		this.price=price;
		this.selltype=selltype;
		this.booktype=booktype;
		this.bookmessage=bookmessage;
		this.press=press;
		this.school=school;
		this.author=author;
	}
	protected String doInBackground(Void... param) {
		List params=new ArrayList();
		params.add(new BasicNameValuePair("ASK","Issue"));
		params.add(new BasicNameValuePair("userid",userid));
		params.add(new BasicNameValuePair("name",name));
		params.add(new BasicNameValuePair("price",price));
		params.add(new BasicNameValuePair("buytype",selltype));
		params.add(new BasicNameValuePair("booktype",booktype));
		params.add(new BasicNameValuePair("explain",bookmessage));
		params.add(new BasicNameValuePair("press",press));
		params.add(new BasicNameValuePair("school",school));
		params.add(new BasicNameValuePair("author",author));
		params.add(new BasicNameValuePair("path",paths));
		params.add(new BasicNameValuePair("ISBN",ISBN));
		PostMessage postMessage=new PostMessage(params);
		String result=postMessage.getResult();
		return result;
	}
	protected void onPostExecute(String result) {
		prodialog.dissmissDialog();
		issuebutton.setEnabled(true);
		if(result.equals("1")){
		issueLayout.setVisibility(View.GONE);
		issuesuccess.setVisibility(View.VISIBLE);
		issuebutton.setVisibility(View.GONE);
		clearbutton.setVisibility(View.GONE);
		}
		else if(result.equals("-1")){
	    Toast.makeText(context, "发送失败,请检查网络配置", Toast.LENGTH_LONG).show();		
		}else if(result.equals("2")){
		final Mydialog diaMydialog=new Mydialog(context, "金豆不足,请签到领取");
		diaMydialog.settitle("提示");
		diaMydialog.setEnsureText("签到");
		diaMydialog.setEnsurelistener(new OnClickListener() {
			public void onClick(View arg0) {
			startActivity(new Intent(activity3.this,Qiandao.class));	
			diaMydialog.dissmissDialog();
			}
		});
		diaMydialog.showDialog();
		}
	}
	
}



@Override
protected void onDestroy() {
	YtTemplate.release(this);
	super.onDestroy();
}
protected void onResume() {
	MobclickAgent.onResume(this);
	super.onResume();
}
protected void onPause() {
	MobclickAgent.onResume(this);
	super.onPause();
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
        if((System.currentTimeMillis()-exitTime) > 2000){  
            Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_LONG).show();                                
            exitTime = System.currentTimeMillis();   
        } else {
         int pid=android.os.Process.myPid();
         android.os.Process.killProcess(pid);
        }
        return true;   
    }
    return super.onKeyDown(keyCode, event);
}


class initEdit extends AsyncTask<Void, Void, String>{
	protected String doInBackground(Void... params) {	
		String vString=sharedPreferences.getString("authorversion","0");
		String version=getversion("author");
		if(!vString.equals(version)){
			 new SaveMessage(context).initPress();
	    }
		sharedPreferences.edit().putString("authorversion", version).commit();
		SaveMessage saveMessage=new SaveMessage(context);
		ArrayList<String> v=saveMessage.getPress();
	    for(int i=0;i<v.size();i++)
	    	pressList.add(v.get(i));
		return null;
	}
	protected void onPostExecute(String result) {
     pressAdapter.notifyDataSetChanged();		
	}
}

public class getAuthor implements Runnable{
	public void run() {
		String vString=sharedPreferences.getString("authorversion","0");
		String version=getversion("author");
		if(!vString.equals(version)){
			sharedPreferences.edit().putString("authorversion", version).commit();
		while(authorsearch==0){
			if(authorsearch==2)
				break;
			authorsearch=2;
			List params=new ArrayList();
			params.add(new BasicNameValuePair("ASK","GetAuthor"));
			params.add(new BasicNameValuePair("find",Author.getText().toString().trim()));
			PostMessage postMessage=new PostMessage(params);
			authorString=postMessage.getResult();
			Message msg=handler.obtainMessage();
			if(!authorString.equals("")){
			msg.what=1;
	        handler.sendMessage(msg);
			}
			authorsearch=1;
		}
	}
		}
}


public class getBookname implements Runnable{
	public void run() {
		String vString=sharedPreferences.getString("booknameversion","0");
		String version=getversion("bookname");
		if(!vString.equals(version)){
			sharedPreferences.edit().putString("booknameversion", version).commit();
		while(booknamesearch==0){
			if(booknamesearch==2)
				break;
			booknamesearch=2;
			List params=new ArrayList();
			params.add(new BasicNameValuePair("ASK","GetBookname"));
			params.add(new BasicNameValuePair("find",bookname.getText().toString().trim()));
			PostMessage postMessage=new PostMessage(params);
			booknameString=postMessage.getResult();
			Message msg=handler.obtainMessage();
			if(!booknameString.equals("")){
			msg.what=2;
	        handler.sendMessage(msg);
			}
			 booknamesearch=1;
		}
		}
	}
}

class Myhandler extends Handler{
	public void handleMessage(Message msg) {
//作者库加载1
if(msg.what==1){
sharedPreferences.edit().putString("author",authorString).commit();
authorList.clear();
String s[]=authorString.split(",");	
for(int i=0;i<s.length;i++){
	authorList.add(s[i]);
}
authorAdapter.notifyDataSetChanged();
//书名库加载2
}else if(msg.what==2){
sharedPreferences.edit().putString("bookname",booknameString).commit();
booknameList.clear();
String s[]=booknameString.split(",");	
for(int i=0;i<s.length;i++){
	booknameList.add(s[i]);
}
booknameAdapter.notifyDataSetChanged();
}else if(msg.what==3){
	startActivityForResult(intent,1);	
	bt1.setEnabled(true);
}

}
}

public String getversion(String name){
	List params=new ArrayList();
	params.add(new BasicNameValuePair("ASK","GetVersion"));
	params.add(new BasicNameValuePair("name",name));
	PostMessage postMessage=new PostMessage(params);
	String result=postMessage.getResult();
	return result;
}


private Intent intent=null;
private class TurnThread implements Runnable{
	public void run() {
		ArrayList<CTextObject> arrayListA=new ReadMessage(context).getTextObject(1);
		ArrayList<CTextObject> arrayListB=new ReadMessage(context).getTextObject(2);
		ArrayList<CTextObject> arrayListC=new ReadMessage(context).getTextObject(3);
		intent=new Intent();
	    intent.putExtra("arrayListA", arrayListA);
		intent.putExtra("arrayListB", arrayListB);
	    intent.putExtra("arrayListC", arrayListC);
		intent.setClass(context, Classification.class);
		Message msg=handler.obtainMessage();
		msg.what=3;
		handler.sendMessage(msg);
	}
}



}


